<template>
  <div class="anime-management">
    <!-- 操作工具栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon> 新增用户
      </el-button>

      <el-button
          type="danger"
          :disabled="!selectedUser.length"
          @click="handleBatchDelete">
        <el-icon><Delete /></el-icon> 批量删除
      </el-button>

      <div class="search-group">
        <el-input
            v-model="searchQuery"
            placeholder="搜索用户昵称"
            clearable
            style="width: 240px"
            @keyup.enter="fetchData"
        />
        <el-button type="primary" @click="fetchData">
          <el-icon><Search /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
        v-loading="loading"
        :data="filteredUsers"
        @selection-change="handleSelectionChange"
        width="100%"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="userId" label="UUID" width="90" sortabl/>
      <el-table-column prop="avatarUrl" label="头像" width="80">
        <template #default="{ row }">
          <AvatarImg :src="row.avatarUrl" />
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" sortable />
      <el-table-column prop="email" label="邮箱" width="200" />
      <el-table-column prop="phone" label="手机号" width="200" />
      <el-table-column label="角色" width="120">
        <template #default="{ row }">
          <el-tag :type="row.userRole === 0 ? 'info' : 'success'">
            {{ row.userRole === 0 ? '普通用户' : 'VIP' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="statusMap[row.userStatus]">
            {{ row.userStatus === 0 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="200" sortable />
      <el-table-column prop="createdAt" label="创建时间" width="180" sortable />
      <el-table-column prop="updatedAt" label="更新时间" width="180" sortable />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[6, 15, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
        v-model="dialog.visible"
        :title="dialog.title"
        width="50%"
    >
      <userFrom
          ref="formRef"
          :form-data="dialog.data"
          @submit="handleSubmit"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Plus, Delete, Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {getUserLoadDataList, PostUserDelete} from "@/api/user.js";
import UserFrom from "@/views/admin/components/userFrom.vue";
import AvatarImg from "@/components/AvatarImg.vue";

// 数据状态
const loading = ref(false)
const searchQuery = ref('')
const selectedUser = ref([])
const formRef = ref(null)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 6,
  total: 0
})

// 弹窗配置
const dialog = reactive({
  visible: false,
  title: '用户信息',
  data: null
})

// 用户数据
const userList = ref([])

// 状态映射
const statusMap = {
  '1': 'warning',
  '0': 'success'
}

// 计算属性
const filteredUsers = computed(() => {
  if (!searchQuery.value) return userList.value
  //在这里实现搜索逻辑，例如使用模糊匹配
  return userList.value.filter(user => user.username.includes(searchQuery.value))
})

// 方法
const fetchData = async () => {
    loading.value = true
  const res = await getUserLoadDataList(pagination.currentPage,pagination.pageSize,1,searchQuery.value)
    userList.value = res.data.list
    pagination.total = res.data.totalCount
    loading.value = false
}
const handleSelectionChange = (selection) => {
  selectedUser.value = selection
}

const handleCreate = () => {
  dialog.title = '新增用户'
  dialog.data = {
    avatarUrl: '',
    email: '',
    lastLogin: '',
    phone: null,
    remark: null,
    userRole: 0,
    userStatus: 0,
    username: ''
  }
  dialog.visible = true
}

const handleEdit = (row) => {
  dialog.title = '编辑用户'
  dialog.data = { ...row }
  dialog.visible = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确定删除 用户：${row.username} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await PostUserDelete(row.userId)
    fetchData()
  })
}

const handleBatchDelete = () => {
  if (!selectedUser.value.length) return

  ElMessageBox.confirm(`确定删除选中的${selectedUser.value.length}位用户吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedUser.value.filter(async (item) => await PostUserDelete(item.userId))
    ElMessage.success(`已删除${ids.length}位用户`)
    fetchData()
  })
}

const handleSubmit = (formData) => {
  if (formData.id) {
    // 更新
    const index = userList.value.findIndex(item => item.id === formData.id)
    userList.value.splice(index, 1, formData)
    ElMessage.success('更新成功')
  } else {
    // 新增
    formData.id = Date.now()
    userList.value.unshift(formData)
    ElMessage.success('添加成功')
  }
  dialog.visible = false
  fetchData()
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.anime-management {
  padding: 20px;
}

.action-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.search-group {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
<style>
.el-dialog{
  margin-top: 4%;
}
</style>
